import { useState, lazy, Suspense } from 'react';
import { Switch, Route, Redirect } from 'react-router-dom';
import { Router } from './RouterAndHistory';
import * as styles from './style.module.less';
import { observer } from 'mobx-react-lite';
import Server from './UIComponents/Server';
import { session } from './session';
import Head from './Head';
import Login from './pages/Login';
import Home from './pages/Home';
import Introduce from './pages/Introduce';
import Setting from './pages/Setting';
import TestUtils from './pages/TestUtils';
import TestTailwindCss from './pages/TestTailwindCSS';
import Debug from 'debug';

const debug = Debug(module.id);

const protectedRoutes = (
  <Suspense fallback={(<div>loading...</div>)}>
    <Switch>
      <Route path='/Home/:id?' render={({ match }) => (<Home id={match.params.id} />)} />
      <Route path='/Setting' component={Setting} />
      <Route path='/page1' component={lazy(() => import('./pages/page1'))} />
      <Route path='/Introduce/:id?' component={Introduce} />
      <Route path='/Server' children={() => (<Server />)} />
      <Route path='/TestUtils' component={TestUtils} />
      <Route path='/TestTailwindCss' component={TestTailwindCss} />
      <Redirect to="/Home" />
    </Switch>
  </Suspense>
);

const WhiteList = [
  '/Server',
  '/TestUtils',
  '/TestTailwindCss',
]

// 直管返回的捕获
window.onpopstate = function (event) {
  debug(`onpopstate event.type = ${event.type}`, event.state, window.location, document.location);
}

function InspectSwitch(p: any) {
  console.log('--- <Switch> ---');
  console.log(p.children);
  console.log(p.children.props.children[0]);
  return p.children;
}

function App() {
  const [count, setCount] = useState(0);

  return (
    <div className={styles.page} >
      <div onClick={() => setCount(v => v + 1)}>Page {count}</div>
      <Router>
        <Head />
        <InspectSwitch>
          <Switch>
            <Route path="/login" exact render={() => (<Login />)} />
            <Route path="/" >
              {({ location }) => {
                debug('in protected', session.userId, !!session.userId);
                if (session.userId || WhiteList.includes(location.pathname)) {
                  return protectedRoutes;
                } else {
                  return (
                    <Redirect from="/" to="/login" />
                  )
                }
              }}
            </Route>
          </Switch>
        </InspectSwitch>
      </Router>
    </div>
  );
}

export default observer(App);

